package com.butterfly.mvc.util;

import com.butterfly.mvc.form.ActionForm;
import com.butterfly.mvc.servlet.MvcBean;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * Created by WOLF on 2016/9/19.
 */
public class Param2Bean {

    public static ActionForm packageParam(HttpServletRequest request){
        Map<String,MvcBean> mvc = (Map<String,MvcBean>)request.getServletContext().getAttribute("mvc");
        MvcBean mvcBean = mvc.get(getPath(request));

        ActionForm bean = null;
        try{
            Class clazz = Class.forName(mvcBean.getFormType());
            bean = (ActionForm) clazz.newInstance();

            Field[] fields = clazz.getDeclaredFields();
            for (Field f:fields){
                f.setAccessible(true);
                f.set(bean,request.getParameter(f.getName()));
                f.setAccessible(false);
            }
        }catch (Exception e){
            System.out.println("封装参数失败");
            e.printStackTrace();
        }
        return bean;
    }

    public static String getPath(HttpServletRequest request){
        return request.getServletPath().split("\\.")[0];
    }

}
